package com.lucene.controller;

import com.alibaba.fastjson.JSONObject;
import com.lucene.model.Image;
import com.lucene.model.Project;
import com.lucene.service.ImageService;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.omg.CORBA.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.UUID;


/**
 * Created by zhangzhen on 25/10/2017.
 */
@RestController
public class ImageController {
    private static Logger logger = Logger.getLogger(ProjectController.class);

    @Autowired
    private ImageService imageService;

    @RequestMapping(value = "/image/uploadImage",method = RequestMethod.POST)
    public @ResponseBody
    String uploadImage(@RequestParam("file") MultipartFile imageFile,
                       @RequestParam("pid") Integer pid){
        JSONObject object = new JSONObject();
        String orname = imageFile.getOriginalFilename();
        String suffix = orname.substring(orname.lastIndexOf(".")+1);
        String src = UUID.randomUUID().toString()+"."+suffix;

        Image image = new Image(pid,src,orname,suffix,
                new Timestamp(System.currentTimeMillis()),
                new Timestamp(System.currentTimeMillis()));
        try {
            image.setBody(imageFile.getBytes());
        }catch (IOException e){
            logger.error("图片转储失败.");
        }

        //获取body
        int rs = imageService.addImages(image);
        if (rs>0){
            object.put("code",0);
            JSONObject data = new JSONObject();
            data.put("src","image/"+image.getSrc());
            data.put("title",image.getTitle());
            object.put("data",data);
            object.put("msg","上传图片成功");
        }else {
            object.put("code",-1);
            object.put("msg","上传图片失败.");
        }
        return object.toJSONString();
    }
    @RequestMapping(value = "/project/image/{src}")
    public void getImageBySrc(@PathVariable("src") String src, HttpServletResponse resp){
        logger.info("src=>"+src);
        Image query = new Image(src);
        Image target = imageService.getImageBySrc(query);
        logger.info(target);
        if (target!=null){
            try {
                resp.setHeader("Pragma", "no-cache");
                resp.setHeader("Cache-Control", "no-cache");
                resp.setDateHeader("Expires", 0);
                resp.setContentType("image/"+target.getSuffix());
                OutputStream output = resp.getOutputStream();
                InputStream in = new ByteArrayInputStream(target.getBody());
                int len;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) != -1) {
                    output.write(buf, 0, len);
                }
                output.flush();
            }catch (IOException e){
                logger.error("image get error.");
            }
        }
    }
}
